var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session=require('express-session');
var bodyParser = require('body-parser');
var hbs=require("hbs");
var login = require('./routes/login');
var index = require('./routes/index');
var admin = require('./routes/admin');
var device = require('./routes/device');
var apps = require('./routes/apps');
var user = require('./routes/user');
var product = require('./routes/product');
var business = require('./routes/business');
var protocoldictionary =require('./routes/protocoldictionary');
var communicationprotocol = require('./routes/communicationprotocol');
var sign = require('./routes/sign.js');
var url = require('url');
var captchapng = require('captchapng');
var svgCaptcha = require('svg-captcha');
var timeout = require('connect-timeout');
var userProtocol = require('./routes/userProtocol');
var syslog = require('./routes/syslog');
var announcement=require('./routes/announcement')

var urlencodedParser = bodyParser.urlencoded({ extended: false })
var app = express(); 
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html',hbs.__express);
app.set('view engine', 'html')
app.use(timeout('15s'));
app.use(logger('dev'));//日志
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  resave:true,//是否允许session重新设置，要保证session有操作的时候必须设置这个属性为true
  rolling:true,//是否按照原设定的maxAge值重设session同步到cookie中，要保证session有操作的时候必须设置这个属性为true
  saveUninitialized: false, //是否设置session在存储容器中可以给修改
  secret: 'nbserver',
  cookie: {maxAge: 1800* 1000}
}));
app.use(express.static(path.join(__dirname, 'public'),{maxAge:1000*60*60*24}));
app.use(function(req,res,next){
  var deviceAgent = req.headers["user-agent"].toLowerCase();
  var pathUrl = req.originalUrl;
  if(deviceAgent.indexOf('windows') == -1){
    req.session.windows=false;
    if(!req.session.user){       //session失效已登陆
        if(pathUrl!='/h5/login' && url.parse(pathUrl).pathname!='/account/getVerifyimg' && pathUrl!='/h5/severError') { //通过判断控制用户登录后不能访问登录页面
            return res.redirect('/h5/login');//页面重定向；
        }else{
          next();
        }
      }else if(req.session.user && pathUrl=='/h5/account/loginOut'){
          delete req.session.user;
          return res.redirect('/h5/login');//页面重定向； 
      }else if(req.session.user && pathUrl=='/'){
          return res.redirect('/h5/index');
      }else{
        next();
      }

  }else{
      req.session.windows=true;
      if(!req.session.user){
        if(pathUrl!='/login' && url.parse(pathUrl).pathname!='/account/getVerifyimg' && pathUrl!='/severError') { //通过判断控制用户登录后不能访问登录页面
            return res.redirect('/login');//页面重定向；
        }else{
          next();
        }
      }else if(req.session.user && pathUrl=='/account/loginOut'){
          delete req.session.user;
          return res.redirect('/login');//页面重定向； 
      }else if(req.session.user && pathUrl=='/h5/index'){
          return res.redirect('/');
      }else{
        next();
      }
  }
   
})

app.get('/severError',function(req,res){
  // delete req.session.user;
  // delete req.session.apikey;
  // delete req.session.role;
  res.render('severError');
})
app.get('/',index);
app.use('/login',login);
app.get('/account/loginOut',function(req,res){
        sign.nullDataReq(req,req.session.apikey,'/sysmanage/account/loginOut',"get",function(ResData){
            if(ResData!=""){
                if(JSON.parse(ResData).statusCode==200){
                  delete req.session.user;
                  delete req.session.apikey;
                  delete req.session.role;
                  res.send(ResData);
                }
            }
        });
});
app.post('/statistics/getStatistics',function(req,res){
  sign.nullDataReq(req,req.session.apikey,'/sysmanage/statistics/getStatistics',"get",function(ResData){
            if(ResData!=""){
                res.send(ResData);
            }
        });
})

app.post('/statistics/getIncreaseDeviceNum',function(req,res){
  sign.dataReq(req,req.body,req.session.apikey,'/sysmanage/statistics/getIncreaseDeviceNum',"get",function(ResData){
            if(ResData!=""){
                  res.send(ResData);
            }
        });
})
app.get('/account/getVerifyimg', function (req, res) {
    var code = '123456789';
    var length = 4;
    var randomcode = '';
    for (var i = 0; i < length; i++) {
        randomcode += code[parseInt(Math.random() * 1000) % code.length];
    }
   //  保存到session
   //  if (null == req.session['loginStatus']) {
   //      req.session["loginStatus"] = {};
   //  }
   //  req.session.loginStatus.randomcode= randomcode;

   // 输出图
   req.session.code = randomcode;
     var p = new captchapng(100,36,parseInt(randomcode)); // width,height,numeric captcha
    p.color(255, 255, 255, 255);  // First color: background (red, green, blue, alpha)
    p.color(65, 65, 65, 255); // Second color: paint (red, green, blue, alpha)
    var img = p.getBase64();
    var imgbase64 = new Buffer(img,'base64');
    res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    res.end(imgbase64);
  // var captcha = svgCaptcha.create({ fontSize: 50, width: 100, height: 40,ignoreChars: '0o1ilOLI', color:false ,noise: 2});
  // req.session.code = captcha.text;
  // res.type('svg');
  // res.status(200).send(captcha.data);
});


app.get('/nbsysmanage/changePasswordPage',function(req,res){
  res.render('changePassword',{'user':req.session.user});
})

app.post('/account/changePassword',function(req,res){
  consolo.log(111222);
  sign.dataReq(req,req.body,req.session.apikey,'/sysmanage/account/changePassword',"post",function(ResData){
      if(ResData!=""){
        res.send(ResData);
      }
  });
})

app.get('/login_timeout',function(req,res){
  res.render('login_timeout');
})

//菜单
app.post('/nbsysmanage/account/getuserMenu',index)

// 业务管理
app.get("/sysmanage/business/list",function(req,res){
  res.render("business/list",{'roleinfo':req.session.role})
})

app.post("/business/editPage",function(req,res){
  res.render("business/add",req.body);
})
app.post("/business/list",business.list);

app.post("/business/getBusiness",business.getBusiness);
app.post("/business/getProtocolList",business.getProtocolList);
app.post("/business/details",function(req,res){
  res.render("business/details",req.body);
})
app.post("/business/del",business.del);
app.post("/business/edit",business.edit);
app.post("/business/getAppList",business.getAppList);
app.post("/product/getAllProduct",business.getAllProduct)
app.post("/business/exportData",business.exportData)
app.post("/business/importData",business.importData)
app.get("/stuinfo/download",function(req,res){
  res.download('public/设备导入模板.xlsx');  
})
//设备管理
app.get("/sysmanage/device/list",function(req,res){
  res.render("devices/list",{'roleinfo':req.session.role});
})


app.post("/devices/list",device.list)
app.post("/devices/getBusinessList",device.getBusinessList)
app.post("/devices/getNetwayList",device.getNetwayList)
// app.post("/devices/getCommunicationProtocolList",device.getCommunicationProtocolList)
app.post("/devices/getDeviceInfo",device.getDeviceInfo)
app.post("/devices/edit",device.edit)
app.post("/devices/datalist",device.datalist)
app.post("/devices/del",device.del)
app.post("/devices/getKtvListBySn",device.getKtvListBySn)
app.post("/devices/getchartdata",device.getchartdata)
app.post("/devices/logList",device.logList)
app.post("/devices/configList",device.configList)
app.get("/device/protocollist",device.protocollist)

app.get("/devices/add",function(req,res){
  res.render("devices/add");
})

app.post("/devices/editPage",function(req,res){
  res.render("devices/add",req.body);
})
app.post("/devices/details",function(req,res){
  res.render("devices/details",req.body);
})
app.post('/devices/datalist/detailsPage',function(req,res){
  if(req.body.privatedata){
    res.render('devices/dataDetails',{'metadata':req.body.metadata,'privatedata':JSON.parse(req.body.privatedata)});
  }else{
    res.render('devices/dataDetails',{'metadata':req.body.metadata});
  }
})
app.post("/devices/chartPage",function(req,res){
  res.render("devices/chart",req.body);
})
app.post("/devices/businesslist",device.businesslist); 


//私有协议管理
app.get('/sysmanage/protocol/list',function(req,res){
  res.render('userProtocol/list',{'roleinfo':req.session.role})
})

app.post("/userProtocol/list",userProtocol.list);

app.post("/userProtocol/editPage",function(req,res){
  res.render("userProtocol/add",req.body);
})
app.post("/userProtocol/addPage",function(req,res){
  res.render("userProtocol/add");
})

app.post("/userProtocol/details",function(req,res){
  res.render("userProtocol/details",req.body);
})

app.post("/userProtocol/getUserProtocol",userProtocol.getUserProtocol);
app.post("/userProtocol/getKtvList",userProtocol.getKtvList);
app.post("/userProtocol/edit",userProtocol.edit)
app.post("/userProtocol/del",userProtocol.del)

//用户管理
app.get("/sysmanage/user/list",function(req,res){
  res.render("user/list");
})
app.get("/sysmanage/user/list",function(req,res){
  res.render("h5/user/list");
})
app.post("/user/list",user.userList)
app.post("/user/editPage",function(req,res){
    res.render("user/add",req.body);
})
app.post("/user/detailsPage",function(req,res){
  res.render("user/details",req.body);
})
app.post("/user/edit",user.userEdit);//数据已经发过去
app.post("/user/del",user.userDel);//数据已经发过去
app.post("/user/getUser",user.userGet);
app.post("/user/getRoleList",user.getRoleList);

//通信协议字典管理
app.get("/sysmanage/communicationprotocol/list",function(req,res){
  res.render("communicationprotocol/list");
}) 
app.post("/communicationprotocol/list",communicationprotocol.communicationprotocolList);//写apps为了避免app同名
app.post("/communicationprotocol/editPage",function(req,res){
  res.render("communicationprotocol/add",req.body);
});
app.post("/communicationprotocol/edit",communicationprotocol.communicationprotocolEdit);
app.post("/communicationprotocol/getprotocol",communicationprotocol.communicationprotocolGet);
app.post("/communicationprotocol/del",communicationprotocol.communicationprotocolDel);
app.post("/communicationprotocol/detail",function(req,res){  //查看私有协议字典详情
 res.render("communicationprotocol/detail",req.body);
});

//产品模块
app.get("/sysmanage/product/getproductlist",function(req,res){
  res.render("product/list");
})
app.post("/product/getproductlist",product.getproductlist);

app.post("/product/editPage",function(req,res){
    res.render("product/add",req.body);
});
app.post("/product/getcommunicationprotocollist",product.getcommunicationprotocollist);

app.post("/product/getProduct",product.getProduct);
app.post("/product/edit",product.edit);
app.post("/product/detail",function(req,res){
    res.render("product/detail",req.body);
});

app.post("/product/del",product.del);
//私有协议字典管理
app.get("/sysmanage/protocoldictionary/list",function(req,res){
  res.render("protocoldictionary/list",{'roleinfo':req.session.role});
}) 
app.post("/protocoldictionary/list",protocoldictionary.protocoldictionaryList);//写apps为了避免app同名
app.post("/protocoldictionary/editPage",function(req,res){
  res.render("protocoldictionary/add",{'id':req.body.id,'roleinfo':req.session.role});
});
app.post("/protocoldictionary/edit",protocoldictionary.protocoldictionaryEdit);
app.post("/protocoldictionary/getktv",protocoldictionary.protocoldictionaryGet);
app.post("/protocoldictionary/del",protocoldictionary.protocoldictionaryDel);
app.post("/protocoldictionary/detail",function(req,res){  //查看私有协议字典详情
 res.render("protocoldictionary/detail",req.body);
});

// //应用平台管理
app.get("/sysmanage/app/list",function(req,res){
  res.render("app/list",{'roleinfo':req.session.role});
})
app.post("/app/details",function(req,res){
  res.render("app/details",req.body);
})
app.post("/app/list",apps.appList);//写apps为了避免app同名
app.post("/app/getApp",apps.appGet);
app.post("/app/editPage",function(req,res){//添加编辑
  res.render("app/add",req.body);
});
app.post("/app/edit",apps.appEdit);//表单提交
app.post("/app/del",apps.appDel);
app.post("/app/testAddress",apps.testAddress);

//系统日志管理
app.get("/sysmanage/syslog/list",function(req,res){
  res.render("syslog/list");
})
app.post("/syslog/list",syslog.syslogList);//写apps为了避免app同名
//公告管理

app.get("/sysmanage/announcement/list",function(req,res){
  res.render("announcement/list");
})
app.post("/announcement/list",announcement.list)
app.post("/announcement/allUser",announcement.allUser)
app.post("/announcement/edit",announcement.edit)
app.post("/announcement/mylist",announcement.mylist)
app.post("/announcement/myAllList",announcement.myAllList)
app.post("/announcement/read",announcement.read)
app.post("/announcement/del",announcement.del)
app.get("/announcement/add",function(req,res){
  res.render("announcement/add");
})

app.get("/announcement/messages",function(req,res){
  res.render("announcement/messages");
})
// h5页面路由
app.use('/h5/login',login);
app.get('/h5/index',function(req,res){
  res.render('h5/index'); 
})
app.get("/h5/business/list",function(req,res){
  res.render("h5/business/list",{'roleinfo':req.session.role})
})
app.get('/h5/business/add',function(req,res){
    if(req.query.id){
        res.render('h5/business/add',{'id':req.query.id});
    }else{
        res.render('h5/business/add');
    }
})
app.get('/h5/business/detail',function(req,res){
  res.render('h5/business/detail',{id:req.query.id});
})
app.get("/h5/app/list",function(req,res){
  res.render("h5/app/list",{'roleinfo':req.session.role})
})
app.get('/h5/app/detail',function(req,res){
  res.render('h5/app/detail',{id:req.query.id});
})
app.get('/h5/app/add',function(req,res){
    if(req.query.id){
        res.render('h5/app/add',{'id':req.query.id});
    }else{
        res.render('h5/app/add');
    }
})
app.get('/h5/changePasswordPage',function(req,res){
  res.render('h5/changePassword',{'user':req.session.user});
})
app.get("/h5/device/list",function(req,res){
  res.render("h5/device/list",{'roleinfo':req.session.role});
})
app.get('/h5/device/detail',function(req,res){
  res.render('h5/device/detail',{sn:req.query.sn});
})

var reqbody='';
app.get('/h5/devices/detailsPage',function(req,res){
  if(reqbody.privatedata){
    res.render('h5/device/dataDetails',{'privatedata':JSON.parse(reqbody.privatedata)});
  }
})
app.post('/h5/devices/detailsPage',function(req,res){
   reqbody = req.body ;
   if(reqbody.privatedata){
    res.render('h5/device/dataDetails',{'privatedata':JSON.parse(reqbody.privatedata)});
  }
   res.render("h5/device/list");
})
app.get('/h5/device/add',function(req,res){
    if(req.query.userId){    //编辑操作打开页面传id
        res.render('h5/device/add',{'userId':req.query.userId,'deviceSn':req.query.deviceSn});
    }else{
        res.render('h5/device/add');
    }
})
app.get('/h5/protocol/list',function(req,res){
  console.log('用户私有协议');
  res.render('h5/userProtocol/list',{'roleinfo':req.session.role})
})
app.get('/h5/protocol/add',function(req,res){
    if(req.query.id){    //编辑操作打开页面传id
        res.render('h5/userProtocol/add',{'id':req.query.id});
    }else{
        res.render('h5/userProtocol/add');
    }
})
app.get("/h5/protocol/detail",function(req,res){
  console.log(req.query);          //get请求用的是query
  console.log('233333332'); 
  res.render("h5/userProtocol/detail",{id:req.query.id});
})
app.get('/h5/severError',function(req,res){
  // delete req.session.user;
  // delete req.session.apikey;
  // delete req.session.role;
  res.render('h5/severError');
})
app.use(haltOnTimedout)
function haltOnTimedout (req, res, next) {
  if (!req.timedout) next()
}
// h5页面路由
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // req.get('Content-Type');
  console.log(req.session.windows)
  console.log(err.status);
  console.log(req.method);
  if(req.session.windows == false && err.status==503 && req.method === 'GET'){
    console.log('11111')
     res.render('h5/severError');
  }else{
    res.status(err.status || 500 );
     if(req.session.windows){
        res.render('error'); 
      }else{
          res.render('h5/error');
      }
    
  }  
});

module.exports = app;
